import re

from yaaps import response

_urls = []

def add_url(pattern, view, name, method=None, form=None, hostname=None):
    _urls.append((re.compile(pattern, re.UNICODE), view, name, method, form, hostname))

def dispatch(request):
    path = request.env['PATH_INFO'].split("?")[0]
    for _url in _urls:
        m = _url[0].match(path)
        if m:
            if _url[3] and _url[3] != request.env['REQUEST_METHOD']:
                continue
            kwargs = m.groupdict()
            args = []
            if _url[4]:
                form = _url[4](request.REQUEST)
                form.validate()
                args.append(form)
            response = _url[1](request, *args, **kwargs)
            return response
    return response.WSGIResponse(headers = {}, content = '', http_status = "404 NOT FOUND")
